package com.dtguai.admin.web.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.dtguai.admin.base.service.impl.BaseServiceImpl;
import com.dtguai.admin.common.error.ErrorCode;
import com.dtguai.admin.common.exception.DefinedException;
import com.dtguai.admin.util.redis.RedisUtil;
import com.dtguai.admin.web.sys.dao.SysDefConfigDao;
import com.dtguai.admin.web.sys.model.SysDefConfig;
import com.dtguai.admin.web.sys.service.SysDefConfigService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
   * @author guoLiang
   * @date 2018-12-11 02:43:01
   */
@Service("sysDefConfigService")
public class SysDefConfigServiceImpl extends BaseServiceImpl<SysDefConfig> implements SysDefConfigService {
	
	@Autowired
	RedisUtil redisUtil;



	@Override
	public void deleteBatchById(List<Integer> ids) {
		Example example = new Example(SysDefConfig.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIn("id",ids);
		((SysDefConfigDao) getMapper()).deleteByExample(example);
	}


	@Override
	public String getValue(String key) {
		SysDefConfig config = redisUtil.getModel(key, SysDefConfig.class);
		if(config == null){
			config = selectByKey(1);
			saveOrUpdateCche(config);
		}

		return config == null ? null : config.getParamValue();
	}
	private void saveOrUpdateCche(SysDefConfig config) {
		if(config == null){
			return ;
		}
		redisUtil.setString(config.getParamKey(), JSON.toJSONString(config));
	}

	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return JSON.parseObject(value, clazz);
		}
		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new DefinedException("获取参数失败", ErrorCode.OSS_ERROR.getCode(),e);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		((SysDefConfigDao) getMapper()).updateValueByKey(key, value);
		redisUtil.delete(key);
	}
}